package com.zygh.sendmail.module.service;

import cn.hutool.core.date.DateUtil;
import com.zygh.sendmail.component.CommonResult;
import com.zygh.sendmail.module.entity.V1RestrictionAlgorithm;
import com.zygh.sendmail.module.mapper.V1RestrictionAlgorithmMapper;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.FileOutputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * java实现邮箱发送邮件功能
 *
 * @author WQ
 */
@Service
public class JavaMailService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private JavaMailSender javaMailSender;
    @Resource
    private V1RestrictionAlgorithmMapper v1RestrictionAlgorithmMapper;

    @Value("${spring.mail.username}")
    private String from;
    @Value("${file.upload}")
    private String upload;

    /**
     * 巡检
     *
     * @return
     */
    public Object patrol() {
        List<String> patrol = v1RestrictionAlgorithmMapper.patrol();
        return new CommonResult().success(patrol);
    }

    /**
     * 发送邮件
     */
    public void mail() {
        //每日巡检结果
        List<String> patrol = v1RestrictionAlgorithmMapper.patrol();
        StringBuilder append = null;
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        //发件人邮箱（发件人邮箱需要获取授权码 可参考：https://blog.csdn.net/silversoldier/article/details/88379733）
        simpleMailMessage.setFrom(from);
        //收件人邮箱
        simpleMailMessage.setTo("msmaoshuaims@163.com");
        simpleMailMessage.setSubject("每日巡检");
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < patrol.size(); i++) {
            append = stringBuilder.append(patrol.get(i) + ",");
        }
        simpleMailMessage.setText(append.toString());
        try {
            javaMailSender.send(simpleMailMessage);
            logger.info("邮件已发送。");
        } catch (Exception e) {
            logger.error("邮件发送失败。" + e.getMessage());
        }

    }


    /**
     * 发送带附件的邮件
     */
    public void sendAttachmentMail() throws Exception {
        Long aLong = this.testHSSF();
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        try {
            // 创建一个multipart格式的message
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
            messageHelper.setFrom(from);
            messageHelper.setTo("msmaoshuaims@163.com");
            messageHelper.setSubject("每日巡检");
            List<String> patrol = v1RestrictionAlgorithmMapper.patrol();
            StringBuilder stringBuilder = new StringBuilder();
            StringBuilder append = null;
            for (int i = 0; i < patrol.size(); i++) {
                append = stringBuilder.append(patrol.get(i) + ",");
            }
            messageHelper.setText(append.toString(), true);
            // 添加附件信息
            String path = upload + File.separator + aLong + ".xls";
            FileSystemResource file = new FileSystemResource(new File(path));
            String fileName = path.substring(path.lastIndexOf(File.separator));
            messageHelper.addAttachment(fileName, file);
            // 发送带附件的邮件
            javaMailSender.send(mimeMessage);
            logger.info("邮件发送成功");
        } catch (Exception e) {
            logger.error("带有附件的邮件发送失败。" + e.getMessage());
        }
    }

    public Long testHSSF() throws Exception {
        // 1. 创建一个工作簿
        HSSFWorkbook wb = new HSSFWorkbook();
        // 2. 创建一个工作表
        HSSFSheet sheet = wb.createSheet("巡检表");
        Row rowTitle = sheet.createRow(0);
        rowTitle.createCell(0).setCellValue("巡检项目");
        rowTitle.createCell(1).setCellValue("巡检数据量");
        rowTitle.createCell(2).setCellValue("巡检时间");
        // 3. 获取数据库数据
        List<String> patrol = v1RestrictionAlgorithmMapper.patrol();
        int i = 1;
        for (String s : patrol) {
            Row row = sheet.createRow(i);
            if (i == 1) {
                row.createCell(0).setCellValue("限行一期接收程序");
            }
            if (i == 2) {
                row.createCell(0).setCellValue("限行一期上传程序");
            }
            if (i == 3) {
                row.createCell(0).setCellValue("限行二期上传程序");
            }
            if (i == 4) {
                row.createCell(0).setCellValue("违停二期");
            }

            row.createCell(1).setCellValue(s);
            row.createCell(2).setCellValue(DateUtil.now());
            i++;
        }
        //  7.写文件
        long l = System.currentTimeMillis();
        FileOutputStream fos = new FileOutputStream(upload + l + ".xls");
        // 8.关闭流
        wb.write(fos);
        fos.close();
        return l;
    }
}
